import { app, shell, BrowserWindow, ipcMain } from 'electron'
import UDPServer from './udp.server'

import FramePacker from './FramePacker'


export default class GPIOServer {
  private _udpServer: UDPServer
  private _framePacker: FramePacker
  constructor(udpServer: UDPServer, framePacker: BrowserWindow) {
    this._udpServer = udpServer
    this._framePacker = framePacker

    this.bindEvent()
  }
  bindEvent() {
    ipcMain.handle('GPIO_TEST', async (event, params) => {

      const parser = (msg, rinfo) => {
        return this._framePacker.unpack(msg, this._framePacker.map.GPIO_MESSAGE)
      }
      const computer = [0x00, 0x00, 0x00, 0x00, 0x00]
      const cmd = 0x00
      const acceptChecker = this._framePacker.map.GPIO_MESSAGE.acceptChecker(params)
      const buffer = this._framePacker.messagePacker(
        this._framePacker.map.GPIO_MESSAGE.sendFormat,
        [
          ...computer,
          params.cpuId,
          params.computerId,
          params.type,
          0x00,
          0x00,
          cmd,
          params.number,
          params.state
        ]
      )
      const link = params.link;
      console.log(link.port, link.host, buffer)
      const result = await this._udpServer.sendAsync(link.port, link.host, buffer, { parser, acceptChecker })
      return result
    })
  }
}
